package com.cmcc.aregister.ui.activity;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.util.IdCardHelper;

public class UserRegisterActivity extends ParentActivity implements
    OnClickListener, OnDateSetListener {
    private final String TAG = "UserRegisterActivity";
    Button registBtn, saveBtn, cancelBtn;
    String url;
    EditText nameT, mobileT, cardT, scardT;
    TextView birthT;
    private ImageView iv_register_man, iv_register_woman;
    private PopupWindow popupWindow;
    private TextView tv_register_certificate_type;
    int sex;
    private int type; // 证件类型下标
    boolean isRegist = false;
    String resultMsg;
    String name, mobile, birth, card, scard, card_type;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int screenWidth;
    private int screenHeight;
    private DatePicker mDatePicker;
    private String result;
    static final int DATE_DIALOG_ID = 1;
    private static final String[] cardTypeValue = new String[] { "01", "02",
        "03", "04" };
    private static final String[] cardTypeText = new String[] { "身份证",
        "港澳台居民身份证", "护照", "军官证" };

    private DatabaseAdapter mDatabaseAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(R.layout.p_user_register);
    }

    @Override
    protected void setupData() {
        Intent i = getIntent();
        if (i != null) {
            mobile = i.getStringExtra("mobile");
        }
    }

    @Override
    protected void setupView() {
        mDatabaseAdapter = new DatabaseAdapter(this);

        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.register_title);
        registBtn = (Button) findViewById(R.id.top_right_btn);
        registBtn.setText(getString(R.string.finish));
        registBtn.setTextSize(18);
        registBtn.setTextColor(getResources().getColor(R.color.blue));
        registBtn.setBackgroundDrawable(null);
        registBtn.setVisibility(View.VISIBLE);
        registBtn.setOnClickListener(this);

        nameT = (EditText) findViewById(R.id.name_et);
        mobileT = (EditText) findViewById(R.id.mobile_et);
        if (mobile != null && !mobile.equals("")) {
            mobileT.setText(mobile);
            mobileT.setEnabled(false);
        }
        birthT = (TextView) findViewById(R.id.birth_et);
        birthT.setOnClickListener(this);
        cardT = (EditText) findViewById(R.id.card_et);
        scardT = (EditText) findViewById(R.id.scard_et);
        iv_register_man = (ImageView) findViewById(R.id.iv_register_man);
        iv_register_man.setOnClickListener(this);
        iv_register_woman = (ImageView) findViewById(R.id.iv_register_woman);
        iv_register_woman.setOnClickListener(this);

        findViewById(R.id.spinner_cardtype).setOnClickListener(this);
        tv_register_certificate_type = (TextView) findViewById(R.id.tv_register_certificate_type);
        initDate();
    }

    private boolean isCheck(String name, String mobile, String birth,
        String card_type, String card, String scard) {
        if (!ConfigUtilHelper.isNotEmpty(name)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.name_is_null),
                getString(R.string.dialog_yes));
            return false;
        }
        else if (!ConfigUtilHelper.isNotEmpty(mobile)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_null), getString(R.string.dialog_yes));
            return false;
        }
        else if (!ConfigUtilHelper.isMobileNum11(mobile)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_err), getString(R.string.dialog_yes));
            return false;
        }
        else if (!ConfigUtilHelper.isNotEmpty(card)) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.card_null), getString(R.string.dialog_yes));
            return false;
        }
        else if ("01".equals(card_type)) {
            if (!IdCardHelper.validateCard(card)) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.idcard_error),
                    getString(R.string.dialog_yes));
                return false;
            }
            else if (("M".equals(IdCardHelper.getGenderByIdCard(card)) && sex != 0)
                || ("F".equals(IdCardHelper.getGenderByIdCard(card)) && sex != 1)) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.card_sex_err),
                    getString(R.string.dialog_yes));
                return false;
            }
            else {
                mYear = IdCardHelper.getYearByIdCard(card);
                mMonth = IdCardHelper.getMonthByIdCard(card);
                mDay = IdCardHelper.getDateByIdCard(card);
                updateDisplay_();
            }
        }
        else if (!ConfigUtilHelper.isNotEmpty(birthT.getText().toString())) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.birth_null), getString(R.string.dialog_yes));
            return false;
        }
        else if (!scard.equals("") && scard.length() != 10) {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.social_card_err),
                getString(R.string.dialog_yes));
            return false;
        }

        return true;
        /**
         * else if(!ConfigUtilHelper.isBirthAndCard(card,birth)){
         * showSingleAlertDlg
         * (getString(R.string.notice),getString(R.string.birth_card_err
         * ),getString(R.string.dialog_yes)); return false; }
         */
    }

    public void showSingleAlertDlg(String title, String msg, String posTitle) {
        new AlertDialog.Builder(this).setTitle(title).setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info).setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).create().show();
    }

    /**
     * 获取注册接口
     * @return
     */
    public String getRegisterUrl() {
        return ConfigUtilHelper.registUrl + "&client_auth="
            + GlobalSetting.CLIENT_AUTH + "&token=" + GlobalSetting.TOKEN
            + "&type=" + GlobalSetting.TYPE + "&name=" + name + "&mobile="
            + mobile + "&birth=" + birth + "&sex=" + sex + "&card=" + card
            + "&social_card=" + scard + "&card_type=" + card_type;
    }

    /**
     * 初始化查询家庭成员资料参数
     * @return
     */
    public Map<String, String> getGetFamillyArg() {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("cid", ConfigUtilHelper.F_cid);
        parameterMap.put("token", ConfigUtilHelper.F_token);
        parameterMap.put("card", card);
        return parameterMap;
    }

    private String f_id;

    /**
     * 初始化修改家庭资料参数
     * @return
     */
    public Map<String, String> updFamilyArg(String f_id) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("cid", ConfigUtilHelper.F_cid);
        parameterMap.put("token", ConfigUtilHelper.F_token);
        parameterMap.put("f_id", f_id);
        parameterMap.put("linkman", name);
        parameterMap.put("phone", mobile);
        parameterMap.put("social_card", scard);
        parameterMap.put("area_id", "");
        parameterMap.put("addr", "");
        parameterMap.put("email", "");
        parameterMap.put("birth", birth);
        return parameterMap;
    }

    /**
     * 解除手机绑定参数
     * @return
     */
    public Map<String, String> untiePhoneArg() {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("cid", ConfigUtilHelper.F_cid);
        parameterMap.put("token", ConfigUtilHelper.F_token);
        parameterMap.put("phone", mobile);
        return parameterMap;
    }

    private final int GET_FAMILLY = 0;
    private final int GET_REGISTER = 1;
    private final int UNTIE_PHONE = 2;
    private final int UPD_FAMILY = 3;
    private int flag = GET_FAMILLY;

    public void doPWork() {
        // 查询用户资料
        flag = GET_FAMILLY;
        showProgressDlg(getString(R.string.notice),
            getString(R.string.info_uploading));
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v == registBtn) {
            name = nameT.getText().toString().trim();
            name = name.replaceAll("\\s*", "");
            mobile = mobileT.getText().toString().trim();
            mobile = mobile.replaceAll("\\s*", "");
            birth = birthT.getText().toString().trim();
            birth = birth.replaceAll("\\s*", "");
            card = cardT.getText().toString().trim();
            card = card.replaceAll("\\s*", "");
            scard = scardT.getText().toString().trim();
            scard = scard.replaceAll("\\s*", "");

            String cardtypeText = cardTypeValue[type];
            card_type = cardTypeValue[type];

            if (isCheck(name, mobile, birth, card_type, card, scard)) {
                String msg = getString(R.string.dialog_regist_sure_again)
                    + "\n" + getString(R.string.msg_name) + name + "\n"
                    + getString(R.string.phoneNumber) + mobile + "\n"
                    + getString(R.string.dlg_card_type) + cardtypeText + "\n"
                    + getString(R.string.dlg_card_txt) + card;
                showDoubleDlg(getString(R.string.notice), msg,
                    getString(R.string.dialog_sure),
                    getString(R.string.dialog_back));
            }
        }
        if (v == birthT) {
            String card_type = cardTypeValue[type];
            String idCardStr = cardT.getText().toString().trim();
            if ("01".equals(card_type)
                && ConfigUtilHelper.isNotEmpty(idCardStr)) {
                boolean flag = IdCardHelper.validateCard(idCardStr);
                if (!flag) {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.idcard_error),
                        getString(R.string.dialog_yes));
                    return;
                }

                mYear = IdCardHelper.getYearByIdCard(idCardStr);
                mMonth = IdCardHelper.getMonthByIdCard(idCardStr);
                mDay = IdCardHelper.getDateByIdCard(idCardStr);
                updateDisplay_();
            }
            else {
                String birth = birthT.getText().toString();
                if (ConfigUtilHelper.isNotEmpty(birth)) {
                    String[] arr = birth.split("-");
                    mYear = Integer.parseInt(arr[0]);
                    mMonth = Integer.parseInt(arr[1]) - 1;
                    mDay = Integer.parseInt(arr[2]);
                }
                showDateSetDialog();
            }

        }
        if (v == cancelBtn) {
            closeDlg();
        }
        if (v == saveBtn) {
            mYear = mDatePicker.getYear();
            mMonth = mDatePicker.getMonth();
            mDay = mDatePicker.getDayOfMonth();
            birthT.setText(new StringBuilder().append(mYear).append("-")
                .append(mMonth + 1).append("-").append(mDay));
            closeDlg();
        }
        //
        if (v.getId() == R.id.iv_register_man) { // man
            sex = 0;
            iv_register_man.setImageResource(R.drawable.register_man_on);
            iv_register_woman.setImageResource(R.drawable.register_woman_off);
        }
        else if (v.getId() == R.id.iv_register_woman) { // woman
            sex = 1;
            iv_register_man.setImageResource(R.drawable.register_man_off);
            iv_register_woman.setImageResource(R.drawable.register_woman_on);
        }
        else if (v.getId() == R.id.spinner_cardtype) {
            new AlertDialog.Builder(this).setItems(cardTypeText,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        tv_register_certificate_type
                            .setText(cardTypeText[arg1]);
                        type = arg1;
                    }
                }).show();
        }
    }

    private void showDateSetDialog() {
        new DatePickerDialog(context, this, mYear, mMonth, mDay).show();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, this, mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DATE_DIALOG_ID:
            ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
            break;
        }
    }

    private void initDate() {
        final Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }

    private void closeDlg() {
        if (popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    private void showProgressDlg(String title, String msg) {
        final ProgressDialog loadingDlg = new ProgressDialog(this);
        loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDlg.setTitle(title);
        loadingDlg.setMessage(msg);
        loadingDlg.setIcon(android.R.drawable.ic_dialog_info);
        loadingDlg.setCancelable(true);
        loadingDlg.show();
        new Thread() {
            public void run() {
                try {
                    progressRun();
                }
                catch (Exception e) {
                    loadingDlg.dismiss();
                }
                loadingDlg.dismiss();
            }
        }.start();
        loadingDlg
            .setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    doWork();
                }

            });
    }

    private void progressRun() {
        if (flag == GET_FAMILLY) {// 查询家庭成员
            result = ConfigUtilHelper.requestPost(
                ConfigUtilHelper.getFamilyUrl, getGetFamillyArg());
        }
        else if (flag == UNTIE_PHONE) {// 解除手机绑定
            result = ConfigUtilHelper.requestPost(ConfigUtilHelper.untiePhone,
                untiePhoneArg());
        }
        else if (flag == UPD_FAMILY) {// 修改家庭成员信息
            result = ConfigUtilHelper.requestPost(
                ConfigUtilHelper.updateFamily, updFamilyArg(f_id));
        }
        else {
            result = ConfigUtilHelper.request(url);
            if (ConfigUtilHelper.debug) {
                Log.i(TAG, "result---->" + result);
            }
            if (result == null) {
                return;
            }
            try {
                JSONObject joson = new JSONObject(result);
                int status = joson.getInt("status");
                resultMsg = joson.getString("message");
                if (ConfigUtilHelper.debug) {
                    Log.i(TAG, "--resultMsg-->" + resultMsg);
                }
                if (status == 0) {
                    isRegist = true;
                }
                else {
                    isRegist = false;
                }
            }
            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void checkInternet() {
        showSingleAlertDlg(getString(R.string.dialog_warning),
            getString(R.string.dialog_check_internet),
            getString(R.string.dialog_close));
    }

    /**
     * 暂时处理解绑手机号或者身份证号
     */
    @Override
    public void _doPWork() {
        // TODO Auto-generated method stub
        super._doPWork();
        flag = UNTIE_PHONE;
        showProgressDlg(getString(R.string.notice),
            getString(R.string.untie_phone_uploading));
    }

    private void doWork() {
        if (flag == GET_FAMILLY) {
            if (result != null) {
                JSONObject joson;
                try {
                    joson = new JSONObject(result);
                    if (joson.getInt("state") > 0) {
                        if (joson.has("family")) {
                            JSONObject j = joson.getJSONObject("family");
                            f_id = j.getString("F_ID");
                            if (j.has("PHONE")) {
                                String phone = j.getString("PHONE");
                                if (phone != null && !phone.equals("")
                                    && !phone.equals("null")) {// 已经存在手机号码
                                    showSingleAlertDlg(R.string.regist_remind);
                                    new AlertDialog.Builder(this)
                                        .setTitle(R.string.notice)
                                        .setMessage(R.string.regist_remind)
                                        .setIcon(
                                            android.R.drawable.ic_dialog_info)
                                        .setCancelable(true)
                                        .setPositiveButton(
                                            R.string.dialog_close,
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                    dialog.dismiss();
                                                }
                                            }).create().show();
                                    /** 由于安全性问题，解绑功能暂时屏蔽，修改为统一由1285006进行受理操作 */
                                    // 解绑
                                    // _showDoubleDlg(getString(R.string.notice),
                                    // "电话号码或身份证已经绑定，是否解绑？",
                                    // getString(R.string.dlg_yes),
                                    // getString(R.string.dlg_no));

                                }
                                else {// 修改家庭成员信息
                                    flag = UPD_FAMILY;
                                    showProgressDlg(getString(R.string.notice),
                                        getString(R.string.info_uploading));
                                }
                            }
                            else {// 修改家庭成员信息
                                flag = UPD_FAMILY;
                                showProgressDlg(getString(R.string.notice),
                                    getString(R.string.info_uploading));
                            }
                        }
                        else {// 直接注册
                            flag = GET_REGISTER;
                            url = getRegisterUrl();
                            showProgressDlg(getString(R.string.notice),
                                getString(R.string.info_uploading));
                        }
                    }
                    else {// 直接注册
                        flag = GET_REGISTER;
                        url = getRegisterUrl();
                        showProgressDlg(getString(R.string.notice),
                            getString(R.string.info_uploading));
                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.regist_err),
                        getString(R.string.dialog_yes));
                }
            }
            else {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.regist_err),
                    getString(R.string.dialog_yes));
            }
        }
        else if (flag == UNTIE_PHONE) {// 解除手机绑定
            if (result != null) {
                JSONObject joson;
                try {
                    joson = new JSONObject(result);
                    if (joson.getInt("state") > 0) {
                        flag = UPD_FAMILY;
                        showProgressDlg(getString(R.string.notice),
                            getString(R.string.update_register_uploading));
                    }
                    else {
                        if (joson.has("msg")) {
                            showSingleAlertDlg(getString(R.string.notice),
                                joson.getString("msg"),
                                getString(R.string.dialog_yes));
                        }
                        else {
                            showSingleAlertDlg(getString(R.string.notice),
                                getString(R.string.untie_err),
                                getString(R.string.dialog_yes));
                        }
                    }
                }
                catch (Exception e) {
                    // TODO: handle exception
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.untie_err),
                        getString(R.string.dialog_yes));
                }
            }
            else {// 解绑失败
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.untie_err),
                    getString(R.string.dialog_yes));
            }
        }
        else if (flag == UPD_FAMILY) {// 修改家庭成员信息
            if (result != null) {
                JSONObject joson;
                try {
                    joson = new JSONObject(result);
                    if (joson.getInt("state") > 0) {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(this.getCurrentFocus()
                                .getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                        showMsg(R.string.regist_success);
                        finish();
                    }
                    else {
                        if (joson.has("msg")) {
                            showSingleAlertDlg(getString(R.string.notice),
                                joson.getString("msg"),
                                getString(R.string.dialog_yes));
                        }
                        else {
                            showSingleAlertDlg(getString(R.string.notice),
                                getString(R.string.update_family_err),
                                getString(R.string.dialog_yes));
                        }
                    }
                }
                catch (Exception e) {
                    // TODO: handle exception
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.update_family_err),
                        getString(R.string.dialog_yes));
                }
            }
            else {// 解绑失败
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.update_family_err),
                    getString(R.string.dialog_yes));
            }
        }
        else {
            if (result == null) {
                if (!connectedNetwork()) {
                    checkInternet();
                }
                return;
            }
            if (isRegist) {
                if (ConfigUtilHelper.isLogin(app)) {
                    long dateMillis = System.currentTimeMillis();
                    String loginDate = Long.toString(dateMillis);
                    mDatabaseAdapter.open_user();
                    Cursor c = mDatabaseAdapter.fetchAllUserData();
                    if (c != null) {
                        if (ConfigUtilHelper.debug) {
                            Log.i(TAG, "--user count----->" + c.getCount());
                        }
                        if (c.getCount() > 0) {
                            mDatabaseAdapter.deleteAllUserData();
                            mDatabaseAdapter.insertUserData(name, mobile,
                                birth, sex, card, scard, loginDate);

                        }
                        else {
                            mDatabaseAdapter.insertUserData(name, mobile,
                                birth, sex, card, scard, loginDate);
                        }
                    }
                }

                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(this.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                showMsg(R.string.regist_success);
                ConfigUtilHelper.has_regist = true;
                ConfigUtilHelper.saveMobileSharedPreferences(this, mobile);
                finish();
            }
            else {
                if (resultMsg == null) {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.regist_err),
                        getString(R.string.dialog_yes));
                }
                else {
                    showSingleAlertDlg(getString(R.string.notice), resultMsg,
                        getString(R.string.dialog_yes));
                }
            }
        }
    }

    /**
     * 更新显示
     */
    private void updateDisplay() {
        birthT.setText(new StringBuilder().append(mYear).append("-")
            .append(mMonth + 1).append("-").append(mDay));
    }

    /**
     * 更新显示
     */
    private void updateDisplay_() {
        String mm = mMonth + "";
        if (mMonth < 10) {
            mm = "0" + mMonth;
        }
        String dd = mDay + "";
        if (mDay < 10) {
            dd = "0" + mDay;
        }
        birthT.setText(new StringBuilder().append(mYear).append("-").append(mm)
            .append("-").append(dd));
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;
        updateDisplay();
    }

}